
var AdminPagesFuncs={
	cpage_blocks: [],
	cpage_content: []
};

/**
 * Function: AdminPagesFuncs.init
 */
AdminPagesFuncs.init=function(obj)
{
	this.pages=obj.pages;
	this.tplaces=obj.tplaces;
	this.cpage_content=obj.cpage_content||[];
	this.l10ns=obj.l10ns;
}

/**
 * Function: AdminPagesFuncs.window_resize
 */
AdminPagesFuncs.window_resize=function()
{
	var wx=win_x();
	if (wx>1300) {
		leftcolw=360;
		rightcolw=wx-620-211-30;
		twocol=true;
	} else {
		if (wx<700) wx=700;
		leftcolw=wx-100-250-200;
		rightcolw=wx-100-250;
		twocol=false;
	}

	if (twocol) {
		$(".af-peditcol1").css("display","inline-block");
		$(".af-peditcol2").css("display","inline-block");
	} else {
		$(".af-peditcol1").css("display","block");
		$(".af-peditcol2").css("display","block");
	}
	$(".af-peditcol1").width(leftcolw+200+60);
	$(".af-peditcol2").width(rightcolw);

	$(".af-peditcol1 .leftcolw1 .af-edit").width(leftcolw);
	$(".af-peditcol1 .leftcolw2 .af-edit").width(leftcolw-10);
	this.rightcolw=rightcolw;
}

/**
 * Function: AdminPagesFuncs.try_update_alias
 */
AdminPagesFuncs.try_update_alias=function()
{
	var val=frm.ajajform("getWidgetValue","alias");
	if (alias_set && val!="") return;
	var parent_id=frm.ajajform("getWidgetValue","parent_id");
	if (!namefield) return;
	var pagename=frm.ajajform("getWidgetValue",namefield);
	var newname="/";
	if (parent_id) {
		var pages=this.pages;
		console.log(pages);
		for (var i=0;i<pages.length;i++) if (pages[i].id==parent_id) newname=pages[i].name.replace(/^\s+/,"");
	}
	if (!pagename) {
		frm.ajajform("setWidgetValue","alias",newname+"/");
		return;
	}
	$.ajax({
		type: "POST",
		url: "/admin-AdminPages/",
		data: {
			mode:"translit",
			ajaj:1,
			value: pagename
		},
		success: function(r) {
			newname+=r;
			newname+="/";
			frm.ajajform("setWidgetValue","alias",newname);
		}
	});
}

/**
 * Function: AdminPagesFuncs.rebuild_blocks
 */
AdminPagesFuncs.rebuild_blocks=function(frm,templateplaces)
{
	var cpage_content=this.cpage_content;
	var l10n_all=this.l10ns;
	console.log({func:"AdminPagesFuncs.rebuild_blocks",frm:frm,templateplaces:templateplaces,cpage_content:cpage_content,l10n_all:l10n_all});
	if (!templateplaces) return;
	var i;
	for (var i=0;i<this.cpage_blocks.length;i++) {
		frm.ajajform("deleteWidget",this.cpage_blocks[i]);
	}
	var arr=[];
	this.cpage_blocks=[];
	for (var li=0;li<l10n_all.length;li++) {i
		var l10n=l10n_all[li];
		for (i=0;i<templateplaces.length;i++) {
			var tp=templateplaces[i];
			var ptc=tp.place_type_code;
			var wysiwyg=false;
			var hh={
				name: "block_"+l10n.id+"__1__"+tp.code,
				label: tp.name+", "+/*tp.place_type_name+", "+*/l10n.name,
				value: cpage_content[l10n.id]?cpage_content[l10n.id][tp.code]:"",
				xpath: ".l10n-"+l10n.id+"-block"
			};
			console.log(hh);
			switch (ptc) {
				case "image":
				case "tmplimage":
					arr[i]=this.rebuild_blocks__image(frm,tp,l10n,hh);
					break;
				case "html":
				case "tmplhtml":
					wysiwyg=true;
				case "text":
				case "tmpltext":
					arr[i]=this.rebuild_blocks__text(frm,tp,wysiwyg,l10n,hh);
					break;
				default:
					console.log("Unknown template place type - "+ptc);
			}
			this.cpage_blocks.push(hh.name);
		}
	}
}

/**
 * Function: AdminPagesFuncs.rebuild_blocks__image
 */
AdminPagesFuncs.rebuild_blocks__image=function(frm,tp,l10n,hh)
{
	hh.type="urledit";
	hh.width="200";
	hh.cssclass="afw-urledit pblock pblock2lines";
	hh.change=function() {};
	return frm.ajajform("insertWidget",null,null,hh);
}

/**
 * Function: AdminPagesFuncs.rebuild_blocks__text
 */
AdminPagesFuncs.rebuild_blocks__text=function(frm,tp,wysiwyg,l10n,hh)
{
	var ah=tp.admin_height;
	if (wysiwyg && ah<5) ah=5;
	hh.type=ah==1?"textedit":"textareaedit";
	if (ah==1) {
//		hh.width=350;
	}
	hh.width=this.rightcolw-50;
	hh.cssclass=(ah==1?"afw-textedit pblock":"afw-textareaedit pblock pblock2lines");
	hh.css='/site.css';
	hh.height=ah*15;
	hh.wysiwyg=wysiwyg;
	hh.change=function() {};
	console.log(hh);
	return frm.ajajform("insertWidget",null,null,hh);
}


var AdminMediaLibraryFuncs={};
/**
 * Function: AdminMediaLibraryFuncs.init_big_previews
 */
AdminMediaLibraryFuncs.init_big_previews=function(icons) {
	var t=this;
	(icons || $(".mainpanel .files img.icon")).bind("click",function() {
		var id=this.parentNode.parentNode.id.replace(/file-/,"");
		for (var i=0;i<t.files.length;i++) {
			var f=t.files[i];
			if (f.id!=id) continue;
			$(".rightpanel .preview img").attr("src",f.icon.replace(/\.(\w+)$/,"-preview6.$1"));
			$(".rightpanel .name").text(f.name);
			$(".rightpanel .size").text(f.filesize);
			$(".rightpanel .url a").attr("href",f.url);
			$(".rightpanel .params").text(""+(f.width?f.width+"x"+f.height:"")+" "+(f.seconds?f.seconds+" seconds":""));
			if (f.url.match(/(jpe?g|png|gif)$/i)) {
				$(".rightpanel .rotate .left").attr("href","/admin-AdminMediaLibrary-rotate_file/?ajaj=1&dir=left&file_id="+f.id);
				$(".rightpanel .rotate .right").attr("href","/admin-AdminMediaLibrary-rotate_file/?ajaj=1&dir=right&file_id="+f.id);
				$(".rightpanel .rotate").show();
			} else {
				$(".rightpanel .rotate").hide();
			}
			$(".rightpanel .view").show();
		}
	});
}

/**
 * Function: AdminMediaLibraryFuncs.open_popup
 */
AdminMediaLibraryFuncs.open_popup=function(options,tinymceoptions) {
	var d=this.global_popup_dialog=$('<div><iframe src="" width="100%" height="95%" frameborder="0" border="0"></iframe></div>').appendTo($("body"));
	this.global_popup_options=options;
	$("iframe",d).attr("src","/admin_popup-AdminMediaLibrary/?target="+options.target);
//	global_ajajform_urledit=t;
	var wx=Math.floor(win_x()*0.90)-100;
	var wy=Math.floor(win_y()*0.90)-100;
	d.dialog({
		modal: true,
		width: wx<830?830:wx,
		height: wy<550?470:wy,
		close: function() { d.dialog("destroy");d.remove(); }
	});
	$(".ui-dialog").css({"z-index":65536});
	this.tinymceoptions=tinymceoptions;
	this.tinymceoptions.dialog=d;
}

/**
 *
 */
AdminMediaLibraryFuncs.submit_tinymce=function(filename)
{
	var t=this.tinymceoptions;
	t.win.document.getElementById(t.field_name).value=filename;
	t.dialog.remove();
	delete this.tinymceoptions;
}


/**
 * Function: AdminMediaLibraryFuncs.init_sizes
 */
AdminMediaLibraryFuncs.init_sizes=function() {
	$(".mainpanel").css({margin: 0,"padding-top":"20px",float:"left",width:win_x()-805});
}

/**
 * Function: AdminMediaLibraryFuncs.init_name_update
 */
AdminMediaLibraryFuncs.init_name_update=function() {
	$(".mainpanel .files .name").bind("click",function() {
		if ($("input",this).length) return;
		var name=$(this).text();
		$(this).empty();
		$("<input type='text' style='width:100%'/>").appendTo($(this)).val(name).bind("keypress",function(e) {
			if (!e) e=event;
			var t=this;
			if (e.keyCode==13) {
				var id=this.parentNode.parentNode.id.replace(/file-/,"");
				var val=$(this).val();
				ajaj_post("/admin-AdminMediaLibrary-file_name_update/",{file_id:id,name:val},function() {
					$(t.parentNode).text(val);
				});
			}
		});
	});
}

/**
 * Function: AdminMediaLibraryFuncs.init_some_dialog
 */

AdminMediaLibraryFuncs.init_some_dialog=function(name) {
	var t=this;
	switch (name) {
		case "edit_folder":
			if (this.edit_folder_frm) return;
			this.edit_folder_frm=$(".edit-folder-dialog .form").ajajform({
				header: "",
				submit: {url: '/admin-AdminMediaLibrary-file_folder_edit/',value: "Save",ajaj: true,params: {id:"",parent_id:"",ajaj:1}}
			});
			for (var i=0;i<this.l10ns.length;i++) {
				this.edit_folder_frm.ajajform("insertWidget",null,null,{type:"textedit",name:this.l10ns[i].id+"__name",label:"Folder name, "+this.l10ns[i].name,minsize:1,width:300,value:""});
			}
			this.edit_folder_frm.ajajform("insertWidget",null,null,{type:"checkbox2",name:"set_code",label:"Set unique code",value:0,showwidgets:["code"]});
			this.edit_folder_frm.ajajform("insertWidget",null,null,{type:"textedit",name:"code",label:"Folder code",width:300,value:""});
			$(".edit-folder-dialog").dialog({autoOpen: false,height: 190+34*this.l10ns.length,width: 560,modal: true});
			break;
		case "upload_file":
			if (this.upload_file_frm) return;
			this.upload_file_frm=$(".upload-file-dialog .form").ajajform({
				header: "",
				submit: {url: '/admin-AdminMediaLibrary-upload_file/',value: "Upload",ajaj: true,params: {file_folder_id:"",ajaj:1}}
			});
			this.upload_file_frm.ajajform("insertWidget",null,null,{type:"fileupload",name:"file",label:"File",width:300,value:"",multiple:false});
			for (var i=0;i<this.l10ns.length;i++) {
				this.upload_file_frm.ajajform("insertWidget",null,null,{type:"textedit",name:this.l10ns[i].id+"__name",label:"File name, "+this.l10ns[i].name,width:300,value:""});
			}
			this.upload_file_frm.ajajform("insertWidget",null,null,{type:"checkbox2",name:"downscale",label:"Scale, if size is bigger than:",value:1,showwidgets:["max_x","max_y"]});
			this.upload_file_frm.ajajform("insertWidget",null,null,{type:"textedit",name:"max_x",label:"Width",width:100,value:"2560"});
			this.upload_file_frm.ajajform("insertWidget",null,null,{type:"textedit",name:"max_y",label:"Height",width:100,value:"2560"});
			$(".upload-file-dialog").dialog({autoOpen: false,height: 260+34*this.l10ns.length,width: 560,modal: true});
			break;
		case "upload_files":
			if (this.upload_files_frm) return;
			this.upload_files_frm=$(".upload-files-dialog .form").ajajform({
				header: "",
				submit: {url: '/admin-AdminMediaLibrary-upload_files/',value: "Upload",ajaj: true,params: {file_folder_id:"",ajaj:1}}
			});
			this.upload_files_frm.ajajform("insertWidget",null,null,{type:"fileupload",name:"file",label:"File",width:300,value:"",multiple:1});
			this.upload_files_frm.ajajform("insertWidget",null,null,{type:"checkbox2",name:"downscale",label:"Scale, if size is bigger than:",value:1,showwidgets:["max_x","max_y"]});
			this.upload_files_frm.ajajform("insertWidget",null,null,{type:"textedit",name:"max_x",label:"Width",width:100,value:"2560"});
			this.upload_files_frm.ajajform("insertWidget",null,null,{type:"textedit",name:"max_y",label:"Height",width:100,value:"2560"});
			$(".upload-files-dialog").dialog({autoOpen: false,height: 260,width: 560,modal: true});
			break;
		case "move_files":
			if (this.move_files_frm) return;
			this.move_files_frm=$(".move-files-dialog .form").ajajform({
				header: "",
				submit: {url: '/admin-AdminMediaLibrary-move_files/',value: "Move files",ajaj: true,params: {ids:"",ajaj:1}}
			});
			this.move_files_frm.ajajform("insertWidget",null,null,{type:"select",name:"file_folder_id",label:"Destination folder",width:300,value:"",values:this.select_all_file_folders});
			$(".move-files-dialog").dialog({autoOpen: false,height: 260,width: 560,modal: true});
			break;
		case "move_file_folders":
			if (this.move_file_folders_frm) return;
			this.move_file_folders_frm=$(".move-file-folders-dialog .form").ajajform({
				header: "",
				submit: {url: '/admin-AdminMediaLibrary-move_file_folders/',value: "Move folders",ajaj: true,params: {ids:"",ajaj:1}}
			});
			this.move_file_folders_frm.ajajform("insertWidget",null,null,{type:"select",name:"file_folder_id",label:"Destination folder",width:300,value:"",values:this.select_foldermove_file_folders, add_null:1});
			$(".move-file-folders-dialog").dialog({autoOpen: false,height: 260,width: 560,modal: true});
			break;
	}
}

/**
 * Function: AdminMediaLibraryFuncs.init_folders
 */
AdminMediaLibraryFuncs.init_folders=function(callback)
{
	var t=this;
	if (this.select_all_file_folders) {
		callback();
		return;
	}
	$("body").append('<div class="AdminMediaLibrary-progress"></div>');
	$.ajax({
		method:"POST",
		url:"/admin_popup-AdminMediaLibrary/",
		data: {ajaj:1,mode:"get_folders"},
		dataType:"json",
		success: function(ret) {
			t.select_all_file_folders=ret;
			t.select_foldermove_file_folders=ret;
			$(".AdminMediaLibrary-progress").remove();
			callback();
		}
	});
}

/**
 * Function: AdminMediaLibraryFuncs.init_buttons
 */
AdminMediaLibraryFuncs.init_buttons=function(file_folder,l10ns,preview_sizes,select_all_file_folders,select_foldermove_file_folders) {
	this.l10ns=l10ns;
	this.file_folder=file_folder;
	this.preview_sizes=preview_sizes;
	var t=this;
	this.preview_sizes=preview_sizes;
	if (!file_folder || !file_folder.id) {
		$(".header .button-upload").hide();
		$(".header .button-upload-many").hide();
		$(".header .button-edit-folder").hide();
	} else {
		$(".header .button-upload").bind("click",function() { t.upload_file();});
		$(".header .button-upload-many").bind("click",function() { t.upload_files();});
		$(".header .button-edit-folder").bind("click",function() { t.edit_file_folder(file_folder);});
	}
	$(".header .button-new-folder").bind("click",function() { t.edit_file_folder({parent_id:file_folder.id});});


	$(".header .button-delete-files").bind("click",function() { t.delete_files(); });
	$(".header .button-move-files").bind("click",function() { t.init_folders(function() { t.move_files();}); });
	$(".header .button-delete-file-folders").bind("click",function() { t.delete_file_folders(); });
	$(".header .button-move-file-folders").bind("click",function() { t.init_folders(function() { t.move_file_folders();}); });
	$(".files input[type='checkbox']").bind("change",function() { t.update_files_buttons(); });
	$(".folders input[type='checkbox']").bind("change",function() { t.update_file_folders_buttons(); });


	$(".header .button-ajajform-file").bind("click",function() { t.submit_ajajform_file(); });
	$(".header .button-ajajform-urledit").bind("click",function() { t.submit_ajajform_urledit(); });
	$(".header .button-ajajform-filegroup").bind("click",function() { t.submit_ajajform_filegroup(); });
	$(".header .button-tinymce").bind("click",function() { t.presubmit_tinymce(); });
	$(".preview-buttons span").bind("click",function() { t.presubmit_tinymce(this); }).css({cursor:"pointer",color:"#4040ff","border-bottom":"1px #4040ff dashed"});

	this.init_sortable();
}

/**
 * Function: AdminMediaLibraryFuncs.init_sortable
 */
AdminMediaLibraryFuncs.init_sortable=function()
{
	$(".files").sortable({
		handle: ".sortable",
		stop: function(event,ui) {
			$.ajax({type: "POST", url: "/admin-AdminMediaLibrary/",data: {ajaj:1,mode: "reorder_files", ids: $(this).sortable('toArray').join(",").replace(/file-/g,"")}});
		}
	});

	$(".folders").sortable({
		handle: ".sortable",
		stop: function(event,ui) {
			$.ajax({type: "POST", url: "/admin-AdminMediaLibrary/",data: {ajaj:1,mode: "reorder_file_folders", ids: $(this).sortable('toArray').join(",").replace(/folder-/g,"")}});
		}
	});
}

/**
 * Function: AdminMediaLibrary.edit_file_folder
 */
AdminMediaLibraryFuncs.edit_file_folder=function(ff)
{
	this.init_some_dialog("edit_folder");
	this.edit_folder_frm.ajajform("setWidgetValue","code",ff.code);
	for (var i=0;i<this.l10ns.length;i++) {
		this.edit_folder_frm.ajajform("setWidgetValue",this.l10ns[i].id+"__name",ff.l10ns?ff.l10ns[this.l10ns[i].id].name:"");
	}
	this.edit_folder_frm.ajajform("setSubmitParam","id",ff.id);
	this.edit_folder_frm.ajajform("setSubmitParam","parent_id",ff.parent_id);
	$( ".edit-folder-dialog" ).dialog( "open" );
}

/**
 * Function: AdminMediaLibrary.upload_file
 */
AdminMediaLibraryFuncs.upload_file=function()
{
	this.init_some_dialog("upload_file");
	for (var i=0;i<this.l10ns.length;i++) {
		this.upload_file_frm.ajajform("setWidgetValue",this.l10ns[i].id+"__name","");
	}
	this.upload_file_frm.ajajform("setSubmitParam","file_folder_id",this.file_folder.id);
	$( ".upload-file-dialog" ).dialog( "open" );
}

/**
 * Function: AdminMediaLibrary.upload_files
 */
AdminMediaLibraryFuncs.upload_files=function()
{
	this.init_some_dialog("upload_files");
	this.upload_files_frm.ajajform("setSubmitParam","file_folder_id",this.file_folder.id);
	$( ".upload-files-dialog" ).dialog( "open" );
}


/**
 * Function: AdminMediaLibrary.move_files
 */
AdminMediaLibraryFuncs.move_files=function()
{
	var ids="";
	var cnt=0;
	var arr=$(".files input[type='checkbox']:checked");
	for (var i=0;i<arr.length;i++) {
		if (ids) ids+=",";
		ids+=arr[i].value;
		cnt++;
	}
	if (ids.length==0) return;
	this.init_some_dialog("move_files",ids);
	this.move_files_frm.ajajform("setSubmitParam","ids",ids);
	$( ".move-files-dialog" ).dialog( "open" );
}

/**
 * Function: AdminMediaLibrary.move_file_folders
 */
AdminMediaLibraryFuncs.move_file_folders=function()
{
	var ids="";
	var cnt=0;
	var arr=$(".folders input[type='checkbox']:checked");
	for (var i=0;i<arr.length;i++) {
		if (ids) ids+=",";
		ids+=arr[i].value;
		cnt++;
	}
	if (ids.length==0) return;
	this.init_some_dialog("move_file_folders");
	this.move_file_folders_frm.ajajform("setSubmitParam","ids",ids);
	$( ".move-file-folders-dialog" ).dialog( "open" );
}

/**
 * Function: AdminMediaLibrary.delete_files
 */
AdminMediaLibraryFuncs.delete_files=function()
{
	var ids="";
	var cnt=0;
	var arr=$(".files input[type='checkbox']:checked");
	for (var i=0;i<arr.length;i++) {
		if (ids) ids+=",";
		ids+=arr[i].value;
		cnt++;
	}
	if (ids.length==0) return;
	if (!confirm("Delete "+cnt+" files?")) return;
	ajaj_href('/admin-AdminMediaLibrary-delete_files/?ajaj=1&ids='+ids);
}

/**
 * Function: AdminMediaLibrary.delete_file_folders
 */
AdminMediaLibraryFuncs.delete_file_folders=function()
{
	var ids="";
	var cnt=0;
	var arr=$(".folders input[type='checkbox']:checked");
	for (var i=0;i<arr.length;i++) {
		if (ids) ids+=",";
		ids+=arr[i].value;
		cnt++;
	}
	if (ids.length==0) return;
	if (!confirm("Delete "+cnt+" folders?")) return;
	ajaj_href('/admin-AdminMediaLibrary-delete_file_folders/?ajaj=1&ids='+ids);
}

/**
 * Function: AdminMediaLibrary.get_checked_files
 */
AdminMediaLibraryFuncs.get_checked_files=function()
{
	var arr=$(".files input[type='checkbox']:checked");
	var ret=[];
	var ids={};
	for (var i=0;i<arr.length;i++) ids[arr[i].value]=1;
	for (var i=0;i<this.files.length;i++) if (ids[this.files[i].id]) ret.push(this.files[i]);
	return ret;
}

/**
 * Function: AdminMediaLibrary.submit_ajajform_file
 */
AdminMediaLibraryFuncs.submit_ajajform_file=function()
{
	var ff=this.get_checked_files();
	if (ff.length!=1) return;
	parent.ajajform_file_id_set({
		id:ff[0].id,
		url:ff[0].url,
		name:ff[0].name
	});
}

/**
 * Function: AdminMediaLibrary.submit_ajajform_urledit
 */
AdminMediaLibraryFuncs.submit_ajajform_urledit=function()
{
	var ff=this.get_checked_files();
	if (ff.length!=1) return;
	parent.ajajform_urledit_set(ff[0].url);
}

/**
 * Function: AdminMediaLibrary.submit_ajajform_filegroup
 */
AdminMediaLibraryFuncs.submit_ajajform_filegroup=function()
{
	var f=[];
	for (var i=0;i<this.files.length;i++) f.push({id:this.files[i].id,name:this.files[i].name,url:this.files[i].url});
	parent.ajajform_file_group_id_set({
		id: this.current_folder.id,
		files:f,
		name: this.current_folder.name
	});
}

/**
 * Function: AdminMediaLibrary.presubmit_tinymce
 */
AdminMediaLibraryFuncs.presubmit_tinymce=function(span)
{
	var url=$(".preview img").attr("src");
	var preview=$(span).attr("alt");
	if (preview==undefined) preview="";
	parent.AdminMediaLibraryFuncs.submit_tinymce(url.replace(/-preview\d+\./,preview+"."));
}

/**
 * Function: AdminMediaLibrary.update_files_buttons
 */
AdminMediaLibraryFuncs.update_files_buttons=function()
{
	var cnt=$(".files input[type='checkbox']:checked").length;
	if (cnt) $(".header .button-delete-files").removeClass("button-disabled"); else $(".header .button-delete-files").addClass("button-disabled");
	if (cnt) $(".header .button-move-files").removeClass("button-disabled"); else $(".header .button-move-files").addClass("button-disabled");
	if (cnt==1) $(".header .button-ajajform-file").removeClass("button-disabled"); else $(".header .button-ajajform-file").addClass("button-disabled");
	if (cnt==1) $(".header .button-ajajform-urledit").removeClass("button-disabled"); else $(".header .button-ajajform-urledit").addClass("button-disabled");
	if (cnt==1) $(".header .button-tinymce").removeClass("button-disabled"); else $(".header .button-tinymce").addClass("button-disabled");
}

/**
 * Function: AdminMediaLibrary.update_file_folders_buttons
 */
AdminMediaLibraryFuncs.update_file_folders_buttons=function()
{
	var cnt=$(".folders input[type='checkbox']:checked").length;
	if (cnt) $(".header .button-delete-file-folders").removeClass("button-disabled"); else $(".header .button-delete-file-folders").addClass("button-disabled");
	if (cnt) $(".header .button-move-file-folders").removeClass("button-disabled"); else $(".header .button-move-file-folders").addClass("button-disabled");
}

var AdminHelperFuncs={};

AdminHelperFuncs.gen_code=function(name,prefix,suffix)
{

}

/**
 * Exel view
 */
$(function() {
	var count = $(".worksheets .item").size();
	console.log( count );
	$(".worksheets .item").each(function(i){
		$(this).css({
			"z-index": count
		});
		count = count - 1;
	});
});
